import {
  getToken
} from "./auth"

// const baseUrl = "http://localhost:8023"
const baseUrl = "http://192.168.0.196:8023"

/**
 * 请求方法
 */
export const HttpMethod = {
  GET: "GET",
  HEAD: "HEAD",
  POST: "POST",
  PUT: "PUT",
  PATCH: "PATCH",
  DELETE: "DELETE",
  OPTIONS: "OPTIONS",
  TRACE: "TRACE"
}

const GET = "GET";
const PUT = "PUT";
const POST = "POST";
const DELETE = "DELETE";
const HEAD = "HEAD";
const OPTIONS = "OPTIONS";
const TRACE = "TRACE";
const CONNECT = "CONNECT";

/**
 * 使用wx.request()执行HTTP请求
 * @param {Object} options - 请求
 * @param {string} options.url - 请求地址 
 * @param {GET | PUT | POST | DELETE | HEAD | OPTIONS | TRACE | CONNECT} options.method - 请求方法
 * @param {Object} options.data - 请求参数
 * @param {boolean} options.isToken - 是否需要 token, 默认 true
 * @param {Object} options.headers - 请求头
 * @returns {Promise} 返回结果
 */
const service = (options) => {
  const {
    url,
    method = HttpMethod.GET,
    data = {},
    isToken = true,
    headers = {}
  } = options;

  // 是否需要设置 token
  if (isToken) {
    headers["Authorization"] = "Bearer " + getToken();
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      method: method,
      data: data,
      header: {
        'Content-Type': 'application/json',
        'platform': 'wechat',
        ...headers
      },
      success(res) {
        const {
          code = -1, msg = "系统错误"
        } = res.data;
        if (code >= 200 && code < 300) {
          // 请求成功的处理
          resolve(res.data);
        } else {
          if (code == 401) {
            wx.reLaunch({
              url: '/pages/login/login',
            });
          }
          reject(`${msg}，状态码${code}`);
        }
      },
      fail(err) {
        // 请求失败的处理
        reject(err);
      }
    });
  });
};

export default service;